// shell输出文字颜色处理插件
// require('colors');
const colors = require('colors/safe');
const mongoose = require('mongoose');

// options参数
const options = {//如不写,会报警告warming
    useNewUrlParser: true,
    useUnifiedTopology: true,
    // 使用And连接的sql语句时汇报警告,所以设置'useFindAndModify'为fasle
    useFindAndModify: false
}


// 连接(mlab)数据库
/*mongoose.connect('mongodb://test:test123456@ds119210.mlab.com:19210/koa-restful-api', {
    useNewUrlParser: true
}).then(() => {
    console.log('数据连接成功')
}).catch(err => {
    console.log(err)
})*/


// const DB_URL = `mongodb://${hostname}:${port}/${dbname}`;
const mongoStr = ` [${colors.rainbow('MongoDB')}] `
mongoose.connect(require('./dbParams'), options).then(() => {
    console.log(colors.bgGreen(`Done`) + mongoStr + colors.green.inverse('连接成功 (^し^)'))
}).catch(err => {
    // 不要throw
    console.error(colors.bgRed(`Done`) + mongoStr + colors.green.inverse('连接失败,还请仔细查找原因!', err))
})

/**
 * TODO: 监听: 可写可不写,没什么用,了解
 * const connection = mongoose.connection;
 * connection.on("connected", () => {// 连接成功}) 
 * connection.on("open", () => {// 数据库开启});
 * connection.on('error', err => {// 链接异常})
 * connection.on('disconnected', () => {// 监听断开链接})
 * mongoose.disconnect(function(){// 主动断开操作})
 */

module.exports = mongoose;